<template>
  <div>
    <!--面包屑区域-->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页
      </el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!--卡片视图区域-->
    <el-card>
      <!--搜索与添加区域-->
        <el-row :gutter="20">
          <el-col :span="7">
            <el-input
              placeholder="请输入内容"
              v-model="queryInfo.query"
              clearable
              @clear="getUserList"
            >
              <el-button
                slot="append"
                icon="el-icon-search"
                @click="searchUserList"
              ></el-button>
            </el-input>
          </el-col>
          <el-col :span="4">
          <el-button type="primary" @click="visible=true">
            新增用户
          </el-button>
        </el-col>
      </el-row>

      <!--用户表格区-->
      <el-table :data="userList" border stripe
                style="width: 100%">
        <el-table-column type="index"
                         label="#"></el-table-column>
        <el-table-column prop="username"
                         label="姓名"></el-table-column>
        <el-table-column prop="mobile"
                         label="电话"></el-table-column>
        <el-table-column prop="role_name"
                         label="角色"></el-table-column>
        <el-table-column prop="email"
                         label="邮箱"></el-table-column>
        <el-table-column label="状态" width="180">
          <template v-slot="scope">
            <el-switch
              v-model="scope.row.mg_state"
              active-color="#409EFF"
              inactive-color="#dcdfe6"
              @change="changeUserState(scope.row)"
            ></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template v-slot="scope">
            <!--修改-->
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="edit(scope.row.id)"
            ></el-button>
            <!--删除-->
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="delete(scope.row.id)"
            ></el-button>
            <!--分配角色-->
            <el-tooltip :enterable="false" effect="dark"
                        content="分配角色"
                        placement="top">
              <el-button
                type="warning"
                icon="el-icon-s-tools"
                size="mini"
                @click="assignRoles(scope.row.id)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <!--分页插件-->
      <el-pagination
        background
        @size-change="getUserList"
        @current-change="getUserList"
        :page-sizes="[1,2,5,10,20,50,100]"
        :current-page.sync="queryInfo.pagenum"
        :page-size.sync="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </el-card>

    <!--新增用户面板-->
    <el-drawer
      title='新增用户'
      :visible.sync="visible"
      direction="rtl"
      ref="drawer"
      :show-close="true"
    >
      <div class="drawer-body">
        <el-form :model="userForm" ref="userForm"
                 :rules="userFormRules"
                 label-width="80px">
          <el-form-item label="用户名" prop="username">
            <el-input v-model="userForm.username"
                      autocomplete="off">

            </el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input show-password
                      v-model="userForm.password"
                      autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="userForm.email"
                      autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="手机" prop="mobile">
            <el-input v-model="userForm.mobile"
                      autocomplete="off"></el-input>
          </el-form-item>
        </el-form>
        <div class="buttons">
          <el-button type="info"
                     @click="resetUserForm">
            重置
          </el-button>
          <el-button
            type="primary"
            @click="addUser"
            :loading="loading"
          >
            {{ loading ? '提交中 ...' : '确定' }}
          </el-button>
        </div>
      </div>
    </el-drawer>
  </div>
</template>

<script>
  export default {
    data () {
      return {
        // 查询用户列表的参数对象
        queryInfo: {
          query: '',
          pagenum: 1,
          pagesize: 2
        },
        //用户列表数据
        userList: [
          {
            id: '',
            username: '',
            email: '',
            mobile: '',
            role_name: '',
            mg_state: false
          }
        ],
        //用户数据总数
        total: 0,
        //控制用户添加面板的显示
        visible: false,
        //控制 添加用户的确定按钮 的loading状态
        loading: false,
        //添加用户的表单数据
        userForm: {
          username: '',
          email: '',
          password: '',
          mobile: '',
          role_name: ''
        },
        //添加用户的表单验证规则
        userFormRules: {
          username: [
            {
              required: true,
              message: '请输入用户名',
              trigger: 'blur'
            },
            {
              min: 6,
              max: 16,
              message: '长度在6-10之间',
              trigger: ['blur', 'change']
            }
          ],
          password: [
            {
              required: true,
              message: '请输入密码',
              trigger: 'blur'
            },
            {
              min: 6,
              max: 16,
              message: '长度在6-16之间',
              trigger: ['blur', 'change']
            }
          ],
          email: [
            {
              required: true,
              message: '请输入邮箱！',
              trigger: 'blur'
            },
            {
              type: 'email',
              message: '邮箱不正确！',
              trigger: ['blur', 'change']
            }
          ],
          mobile: [
            {
              required: true,
              message: '请输入手机号！',
              trigger: 'blur'
            },
            {
              pattern:
                '((13[0-9])|(14[0-9])|(15[0-9])|(16[0-9])|(17[0-9])|(18[0-9])|(19[0-9]))\\d{8}$',
              message: '手机号不正确！',
              trigger: ['blur', 'change']
            }
          ]
        }
      }
    },
    created () {
      this.getUserList()
    },
    methods: {
      // 获取用户列表
      async getUserList () {
        const { data: res } = await this.$http.get('/users', {
          params: this.queryInfo
        })
        if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
        this.userList = res.data.users
        this.total = res.data.total
      },
      //根据搜索条件查询用户
      searchUserList () {
        this.queryInfo.pagenum = 1
        this.getUserList()
      },
      //改变用户账户状态
      async changeUserState (user) {
        console.log(user)
        const { data: res } = await this.$http.put(
          `/users/${user.id}/state/${user.mg_state}`
        )
        if (res.meta.status !== 200) {
          user.mg_state = !user.mg_state
          return this.$message.error(res.meta.msg)
        }
        this.$message.success('更新用户状态成功！')
      },
      //重置添加用户表单
      resetUserForm () {
        this.$refs.userForm.resetFields()
      },
      //新增用户
      async addUser () {
        this.$refs.userForm.validate(async valid => {
          if (!valid) return
          // this.$refs.drawer.closeDrawer()
          this.loading = true // 将提交按钮变为loading状态
          const { data: res } = await this.$http.post(
            '/users',
            this.userForm
          )
          if (res.meta.status !== 201) {
            this.loading = false
            return this.$message.error('添加失败:' + res.meta.msg)
          }
          this.$message({
            showClose: true,
            message: '新增成功',
            type: 'success',
            duration: 1500
          })
          this.loading = true // 将提交按钮变为普通状态
        })

      }
    }

  }
</script>

<style lang="stylus" scoped>
  .btns {
    display flex
    justify-content flex-end
  }

  .buttons {
    display flex
    justify-content flex-end
  }

  .drawer-body {
    width 98%
  }

  .el-drawer span :focus {
    border none
  }
</style>
